local GameObject = class("GameObject")

function GameObject:ctor(obj)
    if not obj then
        obj = CS.UnityEngine.GameObject()
    end
    self:init(obj)
end

function GameObject:init(obj)
    self._view = obj
end

function GameObject:addTo(parent)
    return self
end

function GameObject:getChildren()
    local rect = self:getRectTransform()

    local ret = {}
    for i = 1,rect.childCount do
        local child = rect:GetChild(i-1).gameObject
        table.insert(ret,UI.newObject(child))
    end

    return ret
end

function GameObject:getRectTransform()
    if not self._rect then
        self._rect = self._view:GetComponent(typeof(CS.UnityEngine.Transform));
    end
    return self._rect
end

function GameObject:getComponent(csType)
    return self._view:GetComponent(typeof(csType))
end

function GameObject:removeSelf()
    CS.UnityEngine.Object.DestroyImmediate(self._view)
    self._destroy = true
end

function GameObject:addTo(parent,zorder)
    local myRect = self:getRectTransform()
    local parentRect = parent:getRectTransform()

    myRect:SetParent(parentRect)

    if myRect then
        myRect.anchoredPosition = Vector2(0,0)
        local localPosition = myRect.localPosition
        localPosition.z = 0;

        if parentRect then
            localPosition.x = x or 0
            localPosition.y = y or 0
            localPosition.z = z or 0
        end
        myRect.localPosition = localPosition
    else
        myRect.localPosition = Vector3(0,0,0)
    end
    myRect.localRotation = CS.UnityEngine.Quaternion.identity
    myRect.localScale = Vector3(1,1,1)

    self:setLayerRecursively(self,parent.layer)

    return self
end

function GameObject:pos(x,y)
    local rect = self:getRectTransform()
    local anchoredPosition = rect.anchoredPosition
    anchoredPosition.x = x or 0
    anchoredPosition.y = y or 0
    rect.anchoredPosition = anchoredPosition
    return self
end

function GameObject:setLayerRecursively(obj,layer)
    local rect = self:getRectTransform()
    obj.layer = obj
    for i = 0,rect.childCount - 1 do
        self:setLayerRecursively(rect:GetChild(i).gameObject, layer);
    end
end

function GameObject:anchor(vec2)
    local rect = self:getRectTransform()
    rect.pivot = vec2

    return self
end

function GameObject:size(vec2)
    
end

return GameObject